<template>
  <div>
    <el-card id="box-card">
      <el-card class="vio">
        <video ref="video" autoplay />
      </el-card>
      <el-card class="box">
        <div slot="header" class="clearfix">
          <el-switch
            @change="handleSwitch"
            v-model="value"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="直播模式"
            inactive-text="点击后切换直播"
          >
          </el-switch>
          <!-- <div  v-for="(v,i) in list" :key="i"> {{v}}</div> -->
          <el-table :data="list" style="width: 100%" @cell-click="changevideo">
            <el-table-column prop="data" label="肇事视频" width="180">
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import flvjs from 'flv.js'

export default {
  name: 'home',
  data() {
    return {
      value: true,
      list: [],
      now: -1,
      selected: false
    }
  },
  methods: {
    handleSwitch() {
      if (this.value === true) {
        this.caver(true)
      } else {
        this.caver(false)
      }
    },
    // 图片转canvas
    async caver(model) {
      var mod
      if (model === true) {
        mod = 'live'
      } else {
         mod = 'car'
      }
      var flvPlayer = flvjs.createPlayer({
        type: 'flv',
        url: `http://203.135.98.17:8003/live/${mod}.flv`
      })
      flvPlayer.attachMediaElement(this.$refs.video)
      flvPlayer.load()
      flvPlayer.play()
      await this.axios.post('/api/video/list').then((res) => {
        this.list = this.arrToObj(res.data.obj)
      })
      this.$refs.video.play()
    },
    // 数组转对象
    arrToObj(arr) {
      const obj = []
      arr.forEach((v, i) => {
        const arr = v.substring(0, 10) + '...'
        const bj = { data: arr, index: i }
        obj[i] = bj
      })
      return obj
    },
    // 获取视频
    async changevideo(row) {
      this.value = false
      if (this.selected) {
        this.$message.error('你切换的太快了!')
        return
      }
      await this.axios.get(`/api/video/play/${row.index}`).then((res) => {
        console.log(res.data.message)
        this.now = row.index
        this.$message.success('切换成功,五秒后开始播放!')
        this.selected = true
        setTimeout(() => {
          this.caver()
          this.selected = false
        }, 5000)
      })
    }
  },
  mounted() {
    // this.caver()
    this.handleSwitch()
    // const _this = this
    // this.$refs.video.addEventListener('ended', function (e) {
    //   if (_this.now !== -1)_this.changevideo({ index: -1 })
    // })
  },
  components: {}
}
</script>

<style lang="scss" scoped>
#box-card {
  height: 100vh;
  width: 100%;
  position: relative;
  .vio {
    position: absolute;
    width: 1020px;
    height: 600px;
    video {
      height: 550px;
      width: 980px;
    }
  }
  .box {
    position: absolute;
    right: 10px;
    width: 260px;
    height: 600px;
  }
}
</style>>
